﻿#include "funcloadcontroller.h"
#include <QFileInfo>

FuncLoadController::FuncLoadController()
{
    m_pHelper = DbMgr::instance()->getHelper();
    m_mapFunc.insert("/func/upload/localupload",  &FuncLoadController::localupload);    //本地文件上传
    m_mapFunc.insert("/func/upload/localdownload",  &FuncLoadController::localdownload);    //本地下载
//    m_mapFunc.insert("/func/upload/qcloudupload",  &FuncLoadController::localupload);    //腾讯云上传
//    m_mapFunc.insert("/func/upload/qclouddownload",  &FuncLoadController::localupload);    //腾讯云文件下载
}

void FuncLoadController::service(HttpRequest& request, HttpResponse& response)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));
    QString access_token = request.getParameter("access_token");
    QString username = JwtUtil::getUsername(access_token);
    if(username == NULL || username.isEmpty())
    {
        ret.failedMsg(QStringLiteral("操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }
    SysUser visitUser;
    if(!m_pHelper->selectUserByName(visitUser, username))
    {
        ret.failedMsg(QStringLiteral("用户不存在，操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }

    QByteArray path = request.getPath().toLower();
    if(m_mapFunc.contains(path))
    {
        pServFunc func = m_mapFunc.value(path);
        (this->*func)(request, response, visitUser);
    }
}

//本地文件上传
//http://localhost:9005/func/upload/localupload?access_token=?
//file: (binary)
void FuncLoadController::localupload(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));

    QStringList nameList;
    QMultiMap<QByteArray,QByteArray> paramMap = request.getParameterMap();
    foreach(QByteArray fieldName, paramMap.keys())
    {
        if(fieldName == QString("access_token"))
        {
            continue;
        }
        QString fileName = QString(paramMap.value(fieldName));  //上传文件名
        QTemporaryFile* file = request.getUploadedFile(fieldName);  //上传文件临时存储

        //本地硬盘保存，暂不考虑大文件
        QFileInfo info(fileName);
        QString UUID = QUuid::createUuid().toString().remove("{").remove("}");
        QString localFileName = GlobalFunc::instance()->configDir + "/etc/" +  UUID + "." + info.suffix();
        QFile localFile(localFileName);
        localFile.open(QIODevice::WriteOnly);
        localFile.write(file->readAll());
        localFile.close();

        nameList << localFileName;
    }

    ret.setData(nameList.join(","));
    ResponseUtil::replyJson(response, ret);
}

//http://localhost:9005/func/upload/localdownload?key=D:/project/cpp/QtWebAdmin/etc/4cfd1e70-b54b-4d9f-a459-5dfd22f3f4b9.png&access_token=?
void FuncLoadController::localdownload(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));

    QString keyFileName = request.getParameter("key");
    ResponseUtil::replyFile(response, keyFileName);

}
